package com.zshlong.seckill.mq;


import com.zshlong.seckill.config.RabbitMQConfig;
import com.zshlong.seckill.pojo.SeckillOrder;
import com.zshlong.seckill.pojo.SeckillUser;
import com.zshlong.seckill.service.GoodsService;
import com.zshlong.seckill.service.OrderService;
import com.zshlong.seckill.service.SeckillService;
import com.zshlong.seckill.util.RedisUtil;
import com.zshlong.seckill.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = RabbitMQConfig.SECKILL_QUEUE)
public class MQReceiver {

    private static Logger log = LoggerFactory.getLogger(MQReceiver.class);

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    SeckillService seckillService;

    @RabbitHandler
    public void receive(SeckillMessage message) {
        log.info("receive message:"+message);

        SeckillUser user = message.getUser();
        long goodsId = message.getGoodsId();

        // 判断库存
        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        int stock = goods.getStockCount();
        if(stock <= 0) {
            return;
        }
        // 判断是否已经秒杀到了
        SeckillOrder order = orderService.getSeckillOrderByUserIdGoodsId(user.getId(), goodsId);
        if(order != null) {
            return;
        }
        // 减库存 下订单 写入秒杀订单
        seckillService.seckill(user, goods);
    }
}
